package com.manager.devicemanager.config;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class DataSourceSwitchAspect {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceSwitchAspect.class);
    private static final String DATA_SOURCE_PARAM_NAME = "dataSourceName";

    @Before("execution(* com.manager.devicemanager.service.*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();

        int index = Arrays.asList(parameterNames).indexOf(DATA_SOURCE_PARAM_NAME);
        if (index != -1 && args[index] instanceof String) {
            String dataSourceName = (String) args[index];
            if (dataSourceName != null && !dataSourceName.isEmpty()) {
                DynamicDataSourceContextHolder.push(dataSourceName);
                logger.info("切换到数据源: {}", dataSourceName);
                return;
            }
        }
        logger.info("使用默认数据源");
    }

    @After("execution(* com.manager.devicemanager.service.*.*(..))")
    public void afterMethod() {
        DynamicDataSourceContextHolder.poll();
//        logger.info("清除数据源上下文");
    }
}
